package com.example.test.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT生成token
 * @ClassName: 林文峰
 * @Author Administrator
 * @Date 2020/6/16 0016
 */
public class JWTConfig {

	/**
	 * token生成
	 * @Author: 林文峰 
	 * @Date 2020/6/22 0022 18:59
	 */
	public static String creatJwt(String userId, LocalDateTime time){
		Map header = new HashMap();
		//头部部分，存声明和要用的哈希算法
		header.put("alg","HS256");
		header.put("typ","JWT");
		//消息体，存储一些需要的信息
		JWTCreator.Builder builder = JWT.create();
		builder.withHeader(header)
				.withClaim("iss","service")
				.withClaim("aud","client")
				.withClaim("uiserID",userId);
		//最后一部分，header+payload+secret采用base64编码格式，用哈希算法取摘要,用于保证token完整性
		String admin = builder.withIssuedAt(Date.from(Instant.now()))
				.withExpiresAt(Date.from(time.atZone(ZoneId.systemDefault()).toInstant()))
				.sign(Algorithm.HMAC256("admin"));
		return admin;
	}

	/**
	 * token解析
	 * @Author: 林文峰 
	 * @Date 2020/6/22 0022 18:57
	 */
	public static Map<String, Claim> verifyToken(String token){
		//获取jwt验证器
		JWTVerifier admin = JWT.require(Algorithm.HMAC256("admin")).build();
		//解码token
		DecodedJWT verify = admin.verify(token);
		Map<String, Claim> claims = verify.getClaims();
		return claims;
	}
}
